import wepy from 'wepy';
import base64 from './base64';
import tip from './tip';
import { HOST, APIKEY } from './constant.js'

const fetch = async (params) => {
    let { host, api, data, method, hideLoading } = params;
    if (!hideLoading) {
        tip.loading();
    }
    host = host || HOST;
    method = method ? method.toUpperCase() : 'POST';
    const { username, clientid } = wepy.$instance.globalData && wepy.$instance.globalData.user;
    if (username) {
        data = data || {};
        Object.assign(data, { operator: username })
    }
    const authorization = base64.encode(username + ":" + clientid);
    let res = await wepy.request({
        url: `${host}/${api}`,
        method: method,
        data: data,
        header: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Apikey': `${APIKEY}`, 'Authorization': `${authorization}` },
    });
    /**这里可以追加错误处理 */
    if (!hideLoading) {
        tip.loaded();
    }
    if (res && res.statusCode == 200) {
        res = res.data;
    }
    return res;
};

module.exports = {
    fetch
}
